package com.webex.ta.hydra.core.engine;

import com.webex.ta.hydra.core.*;
import com.webex.ta.hydra.core.HydraParameter;
import com.webex.ta.hydra.core.Keyword;
import com.webex.ta.hydra.exceptions.IllegalKeywordException;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-8-20
 * Time: 13:14:29
 */
public class CommandCompiler {
    public static void compile(TestPlan tp) throws IllegalKeywordException {
        compile(tp.getRoot());
    }

    private static HydraParameter[] toHydraParameter(String... vals) {
        if (vals == null)
            return null;

        HydraParameter[] results = new HydraParameter[vals.length];
        for (int i = 0; i < vals.length; i++) {
            results[i] = new HydraParameter(vals[i]);
        }
        return results;
    }

    public static void compile(Command cmd) {
        String kw = cmd.getKeyword();

        Keyword runtime = KeywordRegistry.getInstance().createKeywordOrMacro(kw);
        runtime.setParameters(toHydraParameter(cmd.getParameters().toArray(new String[0])));
        cmd.setRuntime(runtime);

        if (cmd.hasChild()) {
            for (int i = 0; i < cmd.getChildCount(); i++) {
                compile(cmd.getChildAt(i));
            }
        }
        if (runtime instanceof Controller) {
            for (int i = 0; i < cmd.getChildCount(); i++) {
                ((Controller) runtime).addSubCommand(cmd.getChildAt(i));
            }
        }

    }
}
